package com.gaohc.system.sysuser.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaohc.common.constant.Constants;
import com.gaohc.common.constant.UserConstants;
import com.gaohc.common.core.domain.entity.SysRole;
import com.gaohc.common.core.domain.entity.SysUser;
import com.gaohc.common.core.redis.RedisUtil;
import com.gaohc.common.utils.StringUtils;
import com.gaohc.common.utils.spring.SpringUtils;
import com.gaohc.system.sysuser.domain.SysRoleMenu;
import com.gaohc.system.sysuser.domain.SysUserRole;
import com.gaohc.system.sysuser.mapper.SysRoleMapper;
import com.gaohc.system.sysuser.ISysRoleMenuService;
import com.gaohc.system.sysuser.ISysRoleService;
import com.gaohc.system.sysuser.ISysUserRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 角色 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Resource
    private ISysUserRoleService sysUserRoleService;

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private ISysRoleMenuService roleMenuService;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 根据条件分页查询角色数据
     * 
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    public List<SysRole> selectRoleList(SysRole role)
    {
        return this.list();
    }


    /**
     * 根据用户ID查询权限
     * 
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId)
    {
        List<SysUserRole> list = sysUserRoleService.lambdaQuery().eq(SysUserRole::getUserId, userId).list();
        List<Long> collect = list.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        List<SysRole> perms = lambdaQuery().in(SysRole::getRoleId, collect).list();
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<SysRole> selectRoleAll() {
        return SpringUtils.getAopProxy(this).selectRoleList(new SysRole());
    }

    @Override
    public List<Long> selectRoleListByUserId(Long userId) {
        return roleMapper.selectRoleListByUserId(userId);
    }

    @Override
    public List<SysRole> selectRolesByUserId(Long userId) {
        List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(userId);
        List<SysRole> roles = selectRoleAll();
        for (SysRole role : roles)
        {
            for (SysRole userRole : userRoles)
            {
                if (role.getRoleId().longValue() == userRole.getRoleId().longValue())
                {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public String checkRoleNameUnique(SysRole role)
    {
        long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRole info = lambdaQuery().eq(SysRole::getRoleName, role.getRoleName()).one();
        if (StringUtils.isNotNull(info) && info.getRoleId() != roleId)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkRoleKeyUnique(SysRole role)
    {
        long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRole info = lambdaQuery().eq(SysRole::getRoleKey, role.getRoleKey()).one();
        if (StringUtils.isNotNull(info) && info.getRoleId() != roleId)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean updateRoleById(SysRole role, Long userId) {
        roleMenuService.removeById(role.getRoleId());
        insertRoleMenu(role);
        // 更新缓存用户权限
        if (!SysUser.isAdmin(userId)){
            Collection<String> roleKeys = redisUtil.keys(Constants.LOGIN_ROLE_KEY);
            Collection<String> menuKeys = redisUtil.keys(Constants.LOGIN_MENU_KEY);
            redisUtil.del(roleKeys);
            redisUtil.del(menuKeys);
        }
        return this.updateById(role);
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public void insertRoleMenu(SysRole role)
    {
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds()) {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0) {
            roleMenuService.saveBatch(list);
        }
    }
}
